package com.ruoyi.interfaces.service.impl;


import com.ruoyi.common.constant.AttendanceConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.Base64Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.domain.AttendanceRecordInterface;
import com.ruoyi.domain.TermWorkerQuartz;
import com.ruoyi.interfaces.service.AttendanceMachineService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;


/**
 * 描述:
 *
 * @author 刘松山
 * @date 2021/11/26 15:24
 */
@Service
public class AttendanceMachineServiceImpl implements AttendanceMachineService {
    private static final Logger LOGGER = LoggerFactory.getLogger(AttendanceMachineServiceImpl.class);

    @Autowired
    private RedisCache redisCache;

    @Override
    public int addAttendanceRecord(String data, String SN) {

        List<AttendanceRecordInterface> attendanceRecordList = redisCache.getCacheList("attendanceRecordList");
        if (attendanceRecordList == null) {
            attendanceRecordList = new ArrayList<>();
        }

        String[] array = data.split("\\n");
        int length = array.length;
        LOGGER.info("data:" + array.toString() + "===========length:" + length);
        for (int i = 0; i < length; i++) {
            String[] s = array[i].split("\\t");
            // LOGGER.info("s:"+s.toString()+"===========s[2]:"+s[2]);
            if ("0".equals(s[2])) {

                String idCard = s[0];
                if (redisCache.getCacheObject("idCard:" + idCard) == null) {
                    AttendanceRecordInterface attendanceRecord = new AttendanceRecordInterface();
                    redisCache.setCacheObject("idCard:" + idCard, idCard);
                    redisCache.expire("idCard:" + idCard, AttendanceConstants.idCardExpire);
                    attendanceRecord.setIdCard(idCard);
                    attendanceRecord.setDateTime(s[1]);
                    attendanceRecord.setDeviceNo(SN);
                    attendanceRecord.setLastNum(Long.parseLong(s[10]));
                    attendanceRecordList.add(attendanceRecord);
                }

            }


        }
        if (attendanceRecordList.size() > 0) {
            List<AttendanceRecordInterface> reultList = attendanceRecordList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
                    () -> new TreeSet<>(Comparator.comparing(o -> o.getIdCard() + "_" + o.getDateTime()))),
                    ArrayList::new));

            redisCache.setCacheList("attendanceRecordList", reultList);
        }


        return 1;
    }

    @Override
    public List<String> getTermWorker(String sn) throws UnsupportedEncodingException {

        List<TermWorkerQuartz> termWorkerList = redisCache.getCacheList("termWorker");
        List<TermWorkerQuartz> delTermWorkerList = redisCache.getCacheList("delTermWorker");
        if (termWorkerList == null) {
            return null;
        } else {
            StringBuffer sb = new StringBuffer();
            StringBuffer imgsb = new StringBuffer();
            List<String> cmdList = new ArrayList<>();
            for (TermWorkerQuartz t : termWorkerList) {
                String createTime = DateUtils.parseDateToStr("yyyy-MM-dd", t.getCreateTime());
                String updateTime = "";
                if (null != t.getUpdateTime()) {
                    updateTime = DateUtils.parseDateToStr("yyyy-MM-dd", t.getUpdateTime());
                }
                //当天有新增长期工信息 推送
                if (DateUtils.getDate().equals(createTime)) {
                    //当天推送过的新增 加入缓存 不在重复推送
                    if (null == redisCache.getCacheObject("add_idcard:" + t.getIdCard() + "_" + sn)) {
                        redisCache.setCacheObject("add_idcard:" + t.getIdCard() + "_" + sn, t.getIdCard());
                        redisCache.expire("add_idcard:" + t.getIdCard() + "_" + sn, AttendanceConstants.delIdCardExpire);
                        sb.append("C:" + this.getUUid() + ":DATA");
                        sb.append(" ");
                        sb.append("UPDATE");
                        sb.append(" ");
                        sb.append("USERINFO");
                        sb.append(" ");
                        sb.append("PIN=" + t.getIdCard());
                        sb.append("\t");
                        sb.append("Name=" + new String(t.getWorkerName().getBytes("GB2312"), "GB2312"));
                        sb.append("\t");
                        sb.append("Pri=0");
                        sb.append("\t");
                        sb.append("Passwd=");
                        sb.append("\t");
                        sb.append("Card=");
                        sb.append("\t");
                        sb.append("Grp=");
                        sb.append("\t");
                        sb.append("TZ=");
                        sb.append("\t");
                        sb.append("Verify=");
                        sb.append("\t");
                        sb.append("ViceCard=");
                        sb.append("\t");
                        sb.append("Phone=" + t.getPhoneCode());
                        sb.append("\t");
                        sb.append("Gender=");
                        sb.append("\t");
                        sb.append("Nation=");
                        sb.append("\t");
                        sb.append("IDNum=" + t.getIdCard());
                        sb.append("\n");

                        cmdList.add(sb.toString());
                        sb.setLength(0);
                    }
                }

                if (DateUtils.getDate().equals(updateTime)) {
                    //当天推送过的修改 加入缓存 不在重复推送 但修改可能多次 以更新时间不同区分
                    if (null == redisCache.getCacheObject("mdf_idcard:" + t.getIdCard() + "_" + sn + "_" + t.getUpdateTime().getTime())) {
                        redisCache.setCacheObject("mdf_idcard:" + t.getIdCard() + "_" + sn + "_" + t.getUpdateTime().getTime(), t.getIdCard());
                        redisCache.expire("mdf_idcard:" + t.getIdCard() + "_" + sn + "_" + t.getUpdateTime().getTime(), AttendanceConstants.delIdCardExpire);
                        sb.append("C:" + this.getUUid() + ":DATA");
                        sb.append(" ");
                        sb.append("UPDATE");
                        sb.append(" ");
                        sb.append("USERINFO");
                        sb.append(" ");
                        sb.append("PIN=" + t.getIdCard());
                        sb.append("\t");
                        sb.append("Name=" + new String(t.getWorkerName().getBytes("GB2312"), "GB2312"));
                        sb.append("\t");
                        sb.append("Pri=0");
                        sb.append("\t");
                        sb.append("Passwd=");
                        sb.append("\t");
                        sb.append("Card=");
                        sb.append("\t");
                        sb.append("Grp=");
                        sb.append("\t");
                        sb.append("TZ=");
                        sb.append("\t");
                        sb.append("Verify=");
                        sb.append("\t");
                        sb.append("ViceCard=");
                        sb.append("\t");
                        sb.append("Phone=" + t.getPhoneCode());
                        sb.append("\t");
                        sb.append("Gender=");
                        sb.append("\t");
                        sb.append("Nation=");
                        sb.append("\t");
                        sb.append("IDNum=" + t.getIdCard());
                        sb.append("\n");

                        cmdList.add(sb.toString());
                        sb.setLength(0);
                    }
                }

            }
            //不同命令分多次去推送执行
            if (cmdList.size() > 0) {
                LOGGER.info("cmdList:" + cmdList.toString());
                return cmdList;
            }
            //推送当天新增或者修改时的照片
            cmdList.clear();
            for (TermWorkerQuartz t : termWorkerList) {
                String updateTime = "";
                String createTime = DateUtils.parseDateToStr("yyyy-MM-dd", t.getCreateTime());
                if (null != t.getUpdateTime()) {
                    updateTime = DateUtils.parseDateToStr("yyyy-MM-dd", t.getUpdateTime());
                }
                //当天有新增修改长期工图片信息 推送
                if (DateUtils.getDate().equals(createTime) || DateUtils.getDate().equals(updateTime)) {

                    if (null != t.getImgUrl() && !"".equals(t.getImgUrl())) {
                        String time = "";
                        if (null != t.getUpdateTime()) {
                            time = t.getUpdateTime().getTime() + "";
                        }
                        if (null == redisCache.getCacheObject("img_idcard:" + t.getIdCard() + "_" + sn + "_" + time)) {
                            redisCache.setCacheObject("img_idcard:" + t.getIdCard() + "_" + sn + "_" + time, t.getIdCard());
                            redisCache.expire("img_idcard:" + t.getIdCard() + "_" + sn + "_" + time, AttendanceConstants.delIdCardExpire);
                            //上传长期工照片 Base64转码 注意要和考勤机对应同样编码机制
                            String Content = Base64Convert.GetImageStr(t.getImgUrl());
                            imgsb.append("C:" + this.getUUid() + ":DATA");
                            imgsb.append(" ");
                            imgsb.append("UPDATE");
                            imgsb.append(" ");
                            imgsb.append("BIOPHOTO");
                            imgsb.append(" ");
                            imgsb.append("PIN=" + t.getIdCard());
                            imgsb.append("\t");
                            imgsb.append("Type=9");
                            imgsb.append("\t");
                            imgsb.append("Size=" + Content.length());
                            imgsb.append("\t");
                            imgsb.append("Content=" + Content);
                            imgsb.append("\t");
                            imgsb.append("Format=0");
                            imgsb.append("\t");
                            imgsb.append("Url=");
                            imgsb.append("\t");
                            imgsb.append("PostBackTmpFlag=1");
                            imgsb.append("\n");
                            cmdList.add(imgsb.toString());
                            imgsb.setLength(0);
                        }
                    }
                }
            }
            if (cmdList.size() > 0) {
                LOGGER.info("cmdList:img" + cmdList.toString());
                return cmdList;
            }
            cmdList.clear();
            //删除考勤机上长期工信息 只能一条一条推送执行 不支持多条
            StringBuffer delsb = new StringBuffer();
            for (TermWorkerQuartz t : delTermWorkerList) {
                String delTime = "";
                if (null != t.getDelTime()) {
                    delTime = DateUtils.parseDateToStr("yyyy-MM-dd", t.getDelTime());
                }

                if (DateUtils.getDate().equals(delTime)) {
                    //已经删除了不再重复推送
                    if (null == redisCache.getCacheObject("del_idcard:" + t.getIdCard() + "_" + sn)) {
                        redisCache.setCacheObject("del_idcard:" + t.getIdCard() + "_" + sn, t.getIdCard());
                        redisCache.expire("del_idcard:" + t.getIdCard() + "_" + sn, AttendanceConstants.delIdCardExpire);
                        delsb.append("C:" + this.getUUid() + ":DATA");
                        delsb.append(" ");
                        delsb.append("DELETE");
                        delsb.append(" ");
                        delsb.append("USERINFO");
                        delsb.append(" ");
                        delsb.append("PIN=" + t.getIdCard());
                        cmdList.add(delsb.toString());
                        LOGGER.info(delsb.toString());
                        delsb.setLength(0);
                        break;
                    }
                }
            }

            return cmdList;
        }

    }

    /**
     * @description: 获取16位随机数
     * @author 刘松山
     * @date 2021/11/30 8:47
     */
    public String getUUid() {
        int i = (int) (Math.random() * 90) + 10;
        String s = DateUtils.dateTimeNow() + i;
        return s;
    }
}
